let editor = null;
let ui = {};
let editId = '';
$(document).ready(function () {
    ui.$code = $('#code');
    ui.$mode = $('#modeSelect');
    ui.$btnSubmit = $('#submit');
    ui.$txtTitle = $('#title');
    ui.$txtDesc = $('#desc');
    ui.$change = $('.changeGroup');
    ui.$btnChange = $('#change');
    ui.$btnCancel = $('#cancel');

    ui.$btnSubmit.on('click', submit);
    ui.$btnChange.on('click', submit);
    ui.$btnCancel.on('click', function () {
        ui.$change.hide();
        editId = '';
    });

    editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        lineNumbers: true,
        matchBrackets: true
    });
    ui.$mode.html(`<option value="">选择...</option>`);
    CodeMirror.modeInfo.forEach(v => {
        ui.$mode.html(
            ui.$mode.html() + `<option value="${v.mode}">${v.name}</option>`
        )
    });
    CodeMirror.modeURL = "/codemirror/mode/%N/%N.js"
    ui.$mode.on('change', function () {
        editor.setOption('mode', $(this).val());
        CodeMirror.autoLoadMode(editor, $(this).val());
    });
});

function submit() {
    $.ajax({
        url: '/me/snippet',
        type: 'POST',
        dataType: 'JSON',
        data: {
            id: editId,
            code: editor.getValue(),
            title: ui.$txtTitle.val(),
            desc: ui.$txtDesc.val(),
            mode: editor.getOption('mode')
        }
    }).done(d => {
        alert('完成');
        window.location.reload();
    });
}

function del(id) {
    $.ajax({
        url: '/me/snippet',
        type: 'delete',
        dataType: 'JSON',
        data: {
            id: id
        }
    }).done(d => {
        window.location.reload();
    });
    editId = '';
    ui.$change.hide();
}

function edit(id) {
    $.ajax({
        url: '/me/snippet',
        type: 'get',
        dataType: 'JSON',
        data: {
            id: id
        }
    }).done(d => {
        editId = d._id;
        ui.$mode.val(d.mode);
        editor.doc.setValue(d.code);
        ui.$txtDesc.val(d.desc);
        ui.$txtTitle.val(d.title);
        editor.setOption('mode', d.mode);
        CodeMirror.autoLoadMode(editor, d.mode);
        ui.$change.show();
    });
}

function share(id){
    $('#shareContent').html(htmlEncode(`<script async src="//${window.location.host}/embed/${id}"></script>`));
}   

function htmlEncode( input ) {
    return String(input)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '\'')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}